package cn.microservices.cloud.gateway.web;

import cn.microservices.cloud.gateway.interpector.ip.IpBlackList;
import cn.microservices.cloud.gateway.interpector.rquest.ParamsInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 拦截的操作实体类
 */
@RestController
public class InterceptorController {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private ParamsInterceptor paramsInterceptor;

    @Autowired
    private IpBlackList ipBlackList;

    /**
     * 添加拦截参数
     *
     * @param ip    拦截的参数ip
     * @param key   拦截的参数key
     * @param value 拦截的参数value
     */
    @RequestMapping("add")
    public String add(String ip, String key, String value) {
        if (StringUtils.isEmpty(ip) && (StringUtils.isEmpty(value) || StringUtils.isEmpty(key))) {
            log.warn("添加拦截参数，都为空");
            return "";
        }
        if (!StringUtils.isEmpty(ip)) {
            log.info("添加Ip={}的拦截", ip);
            ipBlackList.addIpBlack(ip);
        }

        if (!StringUtils.isEmpty(value)) {
            log.info("添加参数={}，值={}的拦截", key, value);
            paramsInterceptor.addParamBlack(key, value);
        }

        return "ok";
    }

    /**
     * 删除拦截参数
     *
     * @param ip  拦截的参数ip
     * @param key 拦截的参数key
     */
    @RequestMapping("del")
    public String del(String ip, String key) {
        if (StringUtils.isEmpty(ip) && StringUtils.isEmpty(key)) {
            log.warn("删除拦截参数，都为空");
            return "";
        }
        if (!StringUtils.isEmpty(ip)) {
            log.info("删除Ip={}的拦截", ip);
            ipBlackList.delIpBlack(ip);
        }

        if (!StringUtils.isEmpty(key)) {
            log.info("删除参数={}的拦截", key);
            paramsInterceptor.delParamBlack(key);
        }

        return "ok";
    }


}
